<template>
  <n-card :bordered="false">
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="search_param" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="广告标题">
          <n-input v-model:value="search_param.key" placeholder="请输入广告标题查询" style="width:230px"
                   clearable/>
        </n-form-item>
        <n-form-item label="广告位">
          <n-select v-model:value="search_param.position" :options="positionOption" style="width: 130px;"
                    placeholder="请选择广告位" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="search_param.status" :options="statusOption" style="width: 130px;" clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(search_param.key=null,search_param.status=null,search_param.position=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list"
                :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="search_param"
                list-url="advert/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['advert:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
    <!--新增、修改 -->
    <n-modal v-model:show="addEditModel"
             :title="addEditForm.id?'修改广告':'新增广告'" :mask-closable="false"
             :show-icon="false" preset="dialog" @after-leave="closeAddEditModel" style="width: 1130px">
      <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
              label-width="auto" label-placement="left">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="广告标题" path="title">
            <n-input v-model:value="addEditForm.title" placeholder="请填写广告标题" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="广告位置" path="position">
            <n-select v-model:value="addEditForm.position" :options="positionOption" placeholder="请选择广告位"
                      clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="广告图片" path="src">
            <image-selection v-model:value="addEditForm.src" :width="120" :height="60"/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="广告链接" path="url">
            <n-input v-model:value="addEditForm.url" placeholder="请填写广告链接" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="24" label="广告内容" path="content">
            <editor v-model:value="addEditForm.content" mode="simple"/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="8" label="状态" path="status" :show-feedback="false">
            <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="0" :unchecked-value="1">
              <template #checked>
                正常
              </template>
              <template #unchecked>
                停用
              </template>
            </n-switch>
          </n-form-item-gi>
          <n-form-item-gi :span="8" label="排序" path="sort" :show-feedback="false">
            <n-input-number v-model:value="addEditForm.sort" :show-button="false" placeholder="广告排序" clearable/>
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="()=>(addEditModel=false)">取消</n-button>
          <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>
<script setup lang="ts">
import {ref, reactive, h} from 'vue';
import SearchButtonGroup from '@components/SearchButtonGroup';
import {SelectOption, NPopconfirm, NImage, NTag, FormInst, useMessage} from 'naive-ui';
import DataTable from '@components/DataTable';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';

import {AddSharp} from '@vicons/material';
import {delRequest, postPutRequest} from '@/api/data.ts';


import Editor from '@components/Editor';

import ImageSelection from "@components/ImageSelection";
import {imagePreview} from '@/util';

const message = useMessage()


const positionOption = ref<SelectOption[]>([
  {
    label: '首页',
    value: 0,
  }, {
    label: '列表页',
    value: 1,
  }, {
    label: '详情页',
    value: 2,
  }, {
    label: '资料页',
    value: 3,
  }, {
    label: '个人中心',
    value: 4,
  }
])
const statusOption = ref<SelectOption[]>([
  {
    label: '停用',
    value: 1,
  }, {
    label: '正常',
    value: 0,
  }
])
const search_param = ref({
  key: null,
  position: null,
  status: null,
})
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '标题',
    key: 'title'
  }, {
    title: '广告图片',
    key: 'src',
    width: 100,
    align: 'center',
    render(row: { src: string }) {
      if (row.src) {
        return h(NImage, {
          width: 30,
          height: 30,
          src: imagePreview(row.src)
        })
      }
    }
  }, {
    title: '广告位置',
    key: 'position',
    width: 100,
    render(row: { position: number }) {
      const enabled_text: SelectOption | undefined = positionOption.value.find(obj => obj.value === row.position);
      return h('span', null, {default: () => (enabled_text && enabled_text.label)})
    }
  }, {
    title: '广告链接',
    key: 'url'
  }, {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { status: boolean | number }) {
      const enabled_text: SelectOption | undefined = statusOption.value.find(obj => obj.value === row.status);
      let enabled_color: any = row.status == 0 ? 'success' : 'warning';
      return h(NTag,
          {
            type: enabled_color,
          },
          {
            default: () => (enabled_text && enabled_text.label),
          }
      );
    }
  }, {
    title: '创建时间',
    key: 'createTime',
    width: 175,
  }, {
    title: '更新时间',
    key: 'updateTime',
    width: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width: 120,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          onClick: handleEdit.bind(null, record),
          type: 'primary',
          permission: ['materials:edit'],
        }, {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前广告吗？',
          },
          permission: ['withdrawal:audit'],
        }
      ]
    });
  },
});
//新增、修改数据
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);

const addEditForm = ref({
  id: 0,
  title: null,
  src: null,
  position: null,
  url: <string | null>null,
  content: '',
  status: 0,
  sort: 100,
})
const addEditFormRules = ref({
  title: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写广告标题'
  },
  position: {
    type: 'number',
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择广告位'
  }, src: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择广告图片'
  }, url: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写广告链接'
  },
})

//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.title = record.title;
  addEditForm.value.src = record.src;
  addEditForm.value.position = record.position;
  addEditForm.value.url = record.url;
  addEditForm.value.content = record.content;
  addEditForm.value.status = record.status;
  addEditForm.value.sort = record.sort;
  addEditModel.value = true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('advert/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.title = null;
  addEditForm.value.src = null;
  addEditForm.value.position = null;
  addEditForm.value.url = null;
  addEditForm.value.content = '';
  addEditForm.value.status = 0;
  addEditForm.value.sort = 100;
  handelSubmitLoading.value = false;
}
//保存新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'advert/edit' : 'advert/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
</script>
<style scoped lang="scss">

</style>